package com.isoftstone.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.isoftstone.mapper.PaymentMapper;
import com.isoftstone.mapper.PaymentRecordMapper;
import com.isoftstone.pojo.Payment;
import com.isoftstone.pojo.PaymentRecord;
import com.isoftstone.service.PaymentRecordService;
import com.isoftstone.util.Result;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class PaymentRecordServiceImpl implements PaymentRecordService {
    private final PaymentRecordMapper paymentRecordMapper;
    private final PaymentMapper paymentMapper = null;

    @Autowired
    public PaymentRecordServiceImpl(PaymentRecordMapper paymentRecordMapper) {
        this.paymentRecordMapper = paymentRecordMapper;
    }

    @Override
    public Result<?> insertPaymentRecord(PaymentRecord paymentRecord) {
        int result = paymentRecordMapper.insert(paymentRecord);
        if (result > 0){
            return Result.success("添加成功");
        }
        return Result.error("添加失败");
    }

    @Override
    public Result<?> deletePaymentRecord(Integer id) {
        int result = paymentRecordMapper.deleteById(id);
        if (result > 0){
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }

    @Override
    public Result<?> updatePaymentRecord(Integer id, PaymentRecord paymentRecord) {
        int result = paymentRecordMapper.update(paymentRecord);
        if (result > 0){
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }

    @Override
    public Optional<PaymentRecord> getPaymentRecordById(Integer id) {
        return Optional.ofNullable(paymentRecordMapper.selectById(id));
    }

    @Override
    public Page getAllPaymentRecords(Integer currentPage, Integer pageSize) {
        Page<Payment> page = PageHelper.startPage(currentPage, pageSize);
        paymentRecordMapper.selectAll();
        return page;
    }
    @Override
    public Page getPaymentRecordsByStudentId(String studentNumber,Integer currentPage, Integer pageSize) {
        Page<Payment> page = PageHelper.startPage(currentPage, pageSize);
        paymentRecordMapper.selectByStudentId(studentNumber);
        return page;
    }

    @Override
    public Page getPaymentRecordsByItemName(String ItemName, Integer currentPage, Integer pageSize) {
        Page<Payment> page = PageHelper.startPage(currentPage, pageSize);
        paymentRecordMapper.selectByItemName(ItemName);
        return page;
    }

    @Override
    public Page getPaymentRecordsByStatus(String status,Integer currentPage, Integer pageSize) {
        Page<Payment> page = PageHelper.startPage(currentPage, pageSize);
        paymentRecordMapper.selectByStatus(status);
        return page;
    }

    @Override
    public Page getPaymentRecordsByPaymentMethod(String paymentMethod,Integer currentPage, Integer pageSize) {
        Page<Payment> page = PageHelper.startPage(currentPage, pageSize);
        paymentRecordMapper.selectByPaymentMethod(paymentMethod);
        return page;
    }


    @Override
    public boolean checkPaymentRecord(@Param("studentNumber") String studentNumber,@Param("itemName") String itemName) {
        int count = paymentRecordMapper.checkPaymentRecord(studentNumber, itemName);
        return count > 0;
    }

    @Override
    @Transactional
    public Result<?> pay(PaymentRecord dto) {
        // 1. 先看有没有未支付记录
        PaymentRecord record = paymentRecordMapper.selectUnpaid(dto.getStudentNumber(), dto.getItemName());

        // 2. 没有就 insert 一条
        if (record == null) {
            Payment item = paymentMapper.selectByItemName(dto.getItemName()); // 查应缴金额
            if (item == null) {
                return Result.error("缴费项目不存在");
            }
            PaymentRecord newRec = new PaymentRecord();
            newRec.setStudentNumber(dto.getStudentNumber());
            newRec.setItemName(dto.getItemName());
            newRec.setPayableAmount(item.getAmount());
            newRec.setPaymentMethod(dto.getPaymentMethod());
            paymentRecordMapper.insertUnpaid(newRec);

            // 再查一次拿到主键
            record = paymentRecordMapper.selectUnpaid(dto.getStudentNumber(), dto.getItemName());
        }

        // 3. 统一 update 成已支付
        record.setStatus("已支付");
        record.setPaymentMethod(dto.getPaymentMethod());
        record.setPaymentDate(new Date());
        record.setPaidAmount(record.getPayableAmount());   // 实缴=应缴
        record.setTransactionId(UUID.randomUUID().toString());
        paymentRecordMapper.updateToPaid(record);

        return Result.success("支付成功");
    }
    @Override
    @Transactional
    public Result<?> payAll(PaymentRecord dto) {
        // 1. 获取该学生所有未支付项目
        List<PaymentRecord> unpaidList = paymentRecordMapper.selectUnpaidList(dto.getStudentNumber());

        if (unpaidList.isEmpty()) {
            return Result.success("暂无待缴项目");
        }

        // 2. 循环支付每一个
        String txId = UUID.randomUUID().toString();
        for (PaymentRecord r : unpaidList) {
            r.setStatus("已支付");
            r.setPaymentMethod(dto.getPaymentMethod());
            r.setPaymentDate(new Date());
            r.setPaidAmount(r.getPayableAmount());
            r.setTransactionId(txId);
            paymentRecordMapper.updateToPaid(r);
        }

        return Result.success("支付完成");
    }
    public List<PaymentRecord> getUnpaidList(String studentNumber){
        return paymentRecordMapper.selectUnpaidList(studentNumber);
    }
}
